package com.blank.task19;

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;

public class UserServer {
    public static void main(String[] args) {
        ServerSocket ss = null;
        Socket s = null;
        ObjectInputStream ois = null;
        ObjectOutputStream oos = null;
        UserMessage um = null;
        try {
            //创建ServerSocket类型的对象并提供端口号
            ss = new ServerSocket(8080);

            //等待客户端的连接请求
            System.out.println("等待客户端的连接请求...");
            //当没有客户端连接时，则服务器处于等待状态
            s = ss.accept();
            System.out.println("客户端"+ ss.getInetAddress()+"连接成功!");
            //使用输入输出流进行通信
            //ObjectInputStream类主要用于从输入流中一次性将对象整体读取出来
            ois = new ObjectInputStream(s.getInputStream());
            oos = new ObjectOutputStream(s.getOutputStream());
            um = (UserMessage) ois.readObject();
            //判断um中的User中的user以及password
            if("admin".equalsIgnoreCase(um.getUser().getName()) && "123456".equals(um.getUser().getPassword())){
                um.setType("success");
            }else {
                um.setType("fail");
            }
            System.out.println("状态"+um.getType());
            //发出UserMessage类型的对象
            oos.writeObject(um);
        } catch (IOException | ClassNotFoundException e) {
            e.printStackTrace();
        } finally {
            if(null != oos){
                try {
                    oos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if(null != ois){
                try {
                    ois.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if(null != s){
                try {
                    s.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if(null != ss){
                try {
                    ss.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

    }
}
